IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'MD3.f_Split'))
BEGIN
	DROP FUNCTION MD3.f_Split;
END 
GO

     --Returns a table for the given csv string
     
CREATE FUNCTION MD3.[f_Split] (@csv NVARCHAR(MAX))

   RETURNS @tbl TABLE (Number int identity (1,1), Position int ,Value NVARCHAR(MAX) NOT NULL) 
AS


BEGIN
IF (@csv IS NULL) 
BEGIN
RETURN  
END 

   DECLARE @Position        int,
           @NextPosition   int,
           @ValueLen   int

   SELECT @Position = 0, @NextPosition = 1

   WHILE @NextPosition > 0
   BEGIN
      SELECT @NextPosition = charindex(',', @csv, @Position + 1)
      SELECT @ValueLen = CASE WHEN @NextPosition > 0
                              THEN @NextPosition
                              ELSE len(@csv) + 1
                         END - @Position - 1
      INSERT @tbl (Value,Position)
         VALUES (substring(@csv, @Position + 1, @ValueLen),@Position + 1)
      SELECT @Position = @NextPosition
   END
   RETURN
END
GO
